package cn.springboot.mybatis.dao.configuration;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * 读配置
 *
 * @author junrui.wang
 * @create 2017/9/8
 */

/**
 * 凡是被Spring管理的类，实现接口 EnvironmentAware
 * 重写方法 setEnvironment 可以在工程启动时，获取到系统环境变量和application配置文件中的变量。
 */
//@Configuration
//@EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {

    private RelaxedPropertyResolver propertyResolver;

    @Override
    public void setEnvironment(Environment environment) {
        this.propertyResolver = new RelaxedPropertyResolver(environment, "jdbc.");
    }

    //@Bean(name="getDataSource", destroyMethod="close", initMethod="init")
    public DataSource getDataSource(){
        MysqlDataSource dataSource = new MysqlDataSource();
        System.out.println(propertyResolver.getProperty("url") + "," + propertyResolver.getProperty("user") + "," + propertyResolver.getProperty("pass"));
        dataSource.setURL(propertyResolver.getProperty("url"));
        dataSource.setUser(propertyResolver.getProperty("user"));
        dataSource.setPassword(propertyResolver.getProperty("pass"));
        return dataSource;
    }
}
